package org.pixelami.twisted.spread.pb
{
	import com.hurlant.crypto.hash.MD5;
	import flash.utils.ByteArray;
	import flash.utils.describeType;
	
	public class Utils
	{
		public static function respond(challenge:String, password:String):*
		{
		    /*
		    Respond to a challenge.
			
		    This is useful for challenge/response authentication.
		    */
		    var pba:ByteArray = new ByteArray();
		    var cba:ByteArray = new ByteArray();
		    //TODO - see what happens if we utf-8 this
		    pba.writeMultiByte(password,'iso-8859-1');
		    cba.writeMultiByte(challenge,'iso-8859-1');

			var md5:com.hurlant.crypto.hash.MD5 = new com.hurlant.crypto.hash.MD5();
			pba = md5.hash(pba);
		    pba.writeBytes(cba);
		    
		    var doubleHashedPassword:ByteArray = md5.hash(pba);
		    
		    
		    trace("doubleHashedPassword - "+doubleHashedPassword.toString());
			
			// DO NOT USE ByteArray.toString() method !!!!
		    return bytesToString(doubleHashedPassword);
		}
		
		public static function bytesToString(b:ByteArray):String
		{
			var bstr:String = '';
			for(var i:uint = 0; i < b.length; i++)
			{
				bstr += String.fromCharCode(b[i]);
			}
			return bstr;
		}
		
		public static function challenge():String
		{
		    /*
		    I return some random data.
			*/
			
		    var crap:String = '';
		    /*
		    for x in range(random.randrange(15,25)):
		        crap = crap + chr(random.randint(65,90))
		    crap = md5.new(crap).digest();
		    */
		    return crap;
		    
		}

		public static function qual(obj:Object):String
		{
			var name:String = describeType(obj).@name;
			//trace("Utils.qual - "+name);
			return name;
		}
		
		public function Utils()
		{
		}

		
	}
}